from django.shortcuts import render
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
from . import serializers
from utils.response import APIResponse
from rest_framework.decorators import action
import re
from . import models
from . import throttlings


# Create your views here.


class UserView(ViewSet):
    # 登录接口
    @action(methods=['POST'], detail=False)
    def login(self, request, *args, **kwargs):
        user_ser = serializers.UserSerializer(data=request.data)
        if user_ser.is_valid():
            # user_ser.context["user"]是 user 对象
            username = user_ser.context["user"].username
            token = user_ser.context["token"]
            return APIResponse(username=username, token=token)
        else:
            return APIResponse(code=0, msg=user_ser.errors)

    # 手机号是否存在的接口
    @action(methods=["GET"], detail=False)
    def check_telephone(self, request, *args, **kwargs):
        telephone = request.query_params.get("telephone")
        if re.match("^1(3|4|5|6|7|8|9)\d{9}$", telephone):
            try:
                # get方法，手机号不存在会直接报错的
                models.User.objects.get(telephone=telephone)
                return APIResponse()
            except Exception as e:
                return APIResponse(code=0, msg="手机号不存在")
        else:
            return APIResponse(code=0, msg="手机号不合法")

    @action(methods=['POST'], detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializers.CodeLoginSerializer(data=request.data)
        if ser.is_valid():
            username = ser.context["user"].username
            token = ser.context["token"]
            return APIResponse(username=username, token=token)
        else:
            return APIResponse(code=0, msg=ser.errors)


class SendSmsView(ViewSet):
    throttle_classes = [throttlings.SMSThrottling]

    # 发送验证码接口
    @action(methods=['GET'], detail=False)
    def send(self, request, *args, **kwargs):
        import re
        from luffyapi.libs.tx_sendmessage.send import get_code, send_msg
        from django.core.cache import cache
        from django.conf import settings

        telephone = request.query_params.get("telephone")
        if re.match("^1(3|4|5|6|7|8|9)\d{9}$", telephone):
            code = get_code()
            ret = send_msg(telephone, code, "180")
            # 在缓存中保存验证码
            cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)
            if ret:
                return APIResponse(msg="验证码发送成功")
            else:
                return APIResponse(code=0, msg="验证码发送失败")
        else:
            return APIResponse(code=0, msg="手机号不合法")


class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializers.UserRegisterSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        username = response.data.get("username")
        return APIResponse(msg="注册成功", username=username)